/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FrmQuickConverter.java
 *
 * Created on Aug 12, 2009, 5:31:15 PM
 */
package cconverter;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.DefaultComboBoxModel;
import org.jdesktop.application.Action;

/**
 *
 * @author SapunBoj
 */
public class FrmQuickConverter extends javax.swing.JFrame {

    Double Amount;
    String From;
    String To;
    public Maps maps = new Maps();
    public FrmInfo _frmInfo = new FrmInfo(this, true);
    public Sets _sets = new Sets();
    public Props _props = new Props();

    /** Creates new form FrmQuickConverter */
    public FrmQuickConverter() {
        initComponents();
        myInit();
        fillCombos();
        this.pack();
        this.setVisible(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlLeft = new javax.swing.JPanel();
        lblAmount = new javax.swing.JLabel();
        lblFrom = new javax.swing.JLabel();
        lblTo = new javax.swing.JLabel();
        lblResult = new javax.swing.JLabel();
        txtFrom = new javax.swing.JComboBox();
        txtTo = new javax.swing.JComboBox();
        btnConvert = new javax.swing.JButton();
        txtAmount = new javax.swing.JFormattedTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(cconverter.CConverterApp.class).getContext().getResourceMap(FrmQuickConverter.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N
        setResizable(false);

        pnlLeft.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("pnlLeft.border.title"))); // NOI18N
        pnlLeft.setName("pnlLeft"); // NOI18N

        lblAmount.setText(resourceMap.getString("lblAmount.text")); // NOI18N
        lblAmount.setName("lblAmount"); // NOI18N

        lblFrom.setText(resourceMap.getString("lblFrom.text")); // NOI18N
        lblFrom.setName("lblFrom"); // NOI18N

        lblTo.setText(resourceMap.getString("lblTo.text")); // NOI18N
        lblTo.setName("lblTo"); // NOI18N

        lblResult.setFont(resourceMap.getFont("lblResult.font")); // NOI18N
        lblResult.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblResult.setText(resourceMap.getString("lblResult.text")); // NOI18N
        lblResult.setName("lblResult"); // NOI18N

        txtFrom.setMaximumRowCount(12);
        txtFrom.setName("txtFrom"); // NOI18N
        txtFrom.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                txtFromItemStateChanged(evt);
            }
        });

        txtTo.setMaximumRowCount(12);
        txtTo.setName("txtTo"); // NOI18N
        txtTo.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                txtToItemStateChanged(evt);
            }
        });

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(cconverter.CConverterApp.class).getContext().getActionMap(FrmQuickConverter.class, this);
        btnConvert.setAction(actionMap.get("Convert")); // NOI18N
        btnConvert.setText(resourceMap.getString("btnConvert.text")); // NOI18N
        btnConvert.setName("btnConvert"); // NOI18N

        txtAmount.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.00"))));
        txtAmount.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtAmount.setText(resourceMap.getString("txtAmount.text")); // NOI18N
        txtAmount.setName("txtAmount"); // NOI18N
        txtAmount.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtAmountMouseClicked(evt);
            }
        });
        txtAmount.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtAmountKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout pnlLeftLayout = new javax.swing.GroupLayout(pnlLeft);
        pnlLeft.setLayout(pnlLeftLayout);
        pnlLeftLayout.setHorizontalGroup(
            pnlLeftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlLeftLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlLeftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblResult, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
                    .addGroup(pnlLeftLayout.createSequentialGroup()
                        .addGroup(pnlLeftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblAmount)
                            .addComponent(txtAmount, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlLeftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtFrom, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblFrom))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlLeftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblTo)
                            .addComponent(txtTo, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnConvert)))
                .addContainerGap())
        );
        pnlLeftLayout.setVerticalGroup(
            pnlLeftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlLeftLayout.createSequentialGroup()
                .addGroup(pnlLeftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblAmount)
                    .addComponent(lblFrom)
                    .addComponent(lblTo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlLeftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtAmount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnConvert))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblResult, javax.swing.GroupLayout.DEFAULT_SIZE, 18, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlLeft, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlLeft, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtAmountKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtAmountKeyReleased
        // TODO add your handling code here:
        runConvert();
    }//GEN-LAST:event_txtAmountKeyReleased

    private void txtAmountMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtAmountMouseClicked
        // TODO add your handling code here:
        txtAmount.setFocusable(true);
        txtAmount.selectAll();
    }//GEN-LAST:event_txtAmountMouseClicked

    private void txtFromItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_txtFromItemStateChanged
        // TODO add your handling code here:
        runConvert();
    }//GEN-LAST:event_txtFromItemStateChanged

    private void txtToItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_txtToItemStateChanged
        // TODO add your handling code here:
        runConvert();
    }//GEN-LAST:event_txtToItemStateChanged

    private void runConvert() {
        if (txtAmount.getText().length() > 0 && !Maps._vmap.isEmpty()) {
            if (!txtAmount.getText().endsWith(".")) {// u slucaju da se ne zavrsava na .
                if (this.countIndexOf(txtAmount.getText(), ".") <= 1) {// ako ima jednu ili nijednu tacku
                    this.Convert();
                } else {
                    txtAmount.setText("");
                    new FrmInfo(this, true).setInfo("Error", "Enter amount for converting...");
                }
            }
        }
    }

    public int countIndexOf(String text, String search) {
        int count = 0;
        for (int fromIndex = 0; fromIndex > -1; count++) {
            fromIndex = text.indexOf(search, fromIndex + ((count > 0) ? 1 : 0));
        }
        return count - 1;
    }

    @Action
    public void Convert() {
        From = (String) txtFrom.getSelectedItem().toString().toUpperCase();
        To = (String) txtTo.getSelectedItem().toString().toUpperCase();

        if (!Maps._cmap.isEmpty()) {
            if (txtAmount.getText().length() > 0) {
                if (validateQCF()) {
                    // calculate now :)
                    Amount = Double.parseDouble(txtAmount.getText());
                    double var = Double.parseDouble(Maps._vmap.get(From));
                    double toeuro = Amount / var;

                    BigDecimal racun = new BigDecimal(toeuro * Double.parseDouble(Maps._vmap.get(To))).setScale(Integer.parseInt(_props.getProp("decimalPlaces", "2")), RoundingMode.HALF_UP);
                    String publish = "= " + String.valueOf(racun) + " " + To;
                    lblResult.setText(publish);
                    this.setTitle("Quick Converter " + From + " to " + To);
                } else {
                    _frmInfo.setInfo("Error", "Enter amount for converting...");
                }
            } else {
                _frmInfo.setInfo("Error", "System error!");
            }
        }

    }

    // validate form
    public boolean validateQCF() {
        if (!Maps._cmap.containsKey(From.toUpperCase())) {
            _frmInfo.setInfo("Error", "Currency " + From.toUpperCase() + " not supported.");
            return false;
        }

        if (!Maps._cmap.containsKey(To.toUpperCase())) {
            _frmInfo.setInfo("Error", "Currency " + To.toUpperCase() + " not supported.");
            return false;
        }
        return true;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConvert;
    private javax.swing.JLabel lblAmount;
    private javax.swing.JLabel lblFrom;
    private javax.swing.JLabel lblResult;
    private javax.swing.JLabel lblTo;
    private javax.swing.JPanel pnlLeft;
    private javax.swing.JFormattedTextField txtAmount;
    private javax.swing.JComboBox txtFrom;
    private javax.swing.JComboBox txtTo;
    // End of variables declaration//GEN-END:variables

    private void myInit() {
        this.setLocationRelativeTo(null);
        this.setIconImage(Sets.quickCicon);
    }

    private void fillCombos() {

        ArrayList arrl = new ArrayList();
        arrl.addAll(Maps._cmap.keySet());
        Collections.sort(arrl);
        DefaultComboBoxModel dcbmFrom = (DefaultComboBoxModel) txtFrom.getModel();
        DefaultComboBoxModel dcbmTo = (DefaultComboBoxModel) txtTo.getModel();
        for (Object one : arrl) {
            dcbmFrom.addElement(one);
            dcbmTo.addElement(one);
        }
        txtFrom.setRenderer(new ComboBoxRender());
        txtTo.setRenderer(new ComboBoxRender());
    }
}
